package com.cbtx.tablet.fragments

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.ToastUtils
import com.cbtx.networklib.bean.PageInfo
import com.cbtx.tablet.App
import com.cbtx.tablet.R
import com.cbtx.tablet.adapter.GoodsAdapter
import com.cbtx.tablet.ui.GoodsDetailActivity
import com.cbtx.tablet.adapter.RenZhengAdapter
import com.cbtx.tablet.bean.GoodsItemBean
import com.cbtx.tablet.constant.HttpConstant
import com.cbtx.tablet.ui.SpaceItemDecoration
import com.cbtx.tablet.util.DataCacheUtil
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.sp_fragment_renzheng.*

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/5 4:07 AM
 * desc   :
 */
class GoodsTreasureFragment : CommonFragment() {
    private val pageInfo = PageInfo()
    lateinit var mAdapter: GoodsAdapter
    lateinit var goodsTreasureList: List<GoodsItemBean>

    override fun setLayout(): Any = R.layout.sp_fragment_renzheng

    override fun initView(view: View?, savedInstanceState: Bundle?) {
        initView()
        initAdapter()
        initRefreshLayout()
        initLoadMore()
    }

    private fun initView() {

        mTvTips1.text = "收藏宝"
        mIvBg.setImageResource(R.mipmap.sp_bg2)

        mTvCode.text = "云屏编码:${App.androidId}"
        pageInfo.page = 1

        mRvRenZheng.layoutManager = GridLayoutManager(activity, 4)
        mRvRenZheng.addItemDecoration(SpaceItemDecoration(16))
    }

    private fun initAdapter() {
        mAdapter = GoodsAdapter()
        mRvRenZheng.adapter = mAdapter
        mAdapter.setOnItemClickListener { adapter, _, position ->
            val intent = Intent(activity, GoodsDetailActivity::class.java)
            intent.putExtra("authItem", adapter.getItem(position) as GoodsItemBean)
            startActivity(intent)
        }

        goodsTreasureList = DataCacheUtil.readGoodsTreasureList()
        if (goodsTreasureList.isNotEmpty()) {
            mAdapter.setList(goodsTreasureList)
        }
    }

    private fun initRefreshLayout() {
        mRefreshView.setColorSchemeColors(Color.rgb(47, 223, 189))
        mRefreshView.setOnRefreshListener {
            if (NetworkUtils.isConnected()) {
                refresh()
            } else {
                mRefreshView.isRefreshing = false
            }
        }
    }

    /**
     * 初始化加载更多
     */
    private fun initLoadMore() {
        mAdapter.loadMoreModule.setOnLoadMoreListener {
            if (NetworkUtils.isConnected()) {
                loadMore()
            }
        }
        mAdapter.loadMoreModule.isAutoLoadMore = true
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        mAdapter.loadMoreModule.isEnableLoadMoreIfNotFullPage = true
    }

    /**
     * 刷新
     */
    private fun refresh() {
        // 这里的作用是防止下拉刷新的时候还可以上拉加载
        mAdapter.loadMoreModule.isEnableLoadMore = true
        // 下拉刷新，需要重置页数
        pageInfo.reset()
        loadData()
    }

    private fun loadMore() {
        loadData()
    }

    @SuppressLint("CheckResult")
    private fun loadData() {
        val params: MutableMap<String, Any> = HashMap()
        params["pageNum"] = pageInfo.page
        params["pageSize"] = pageInfo.pageSize
        params["type"] = "3"

        App.sApiServiceHolder.getApiService(HttpConstant.CONTENT_ALIAS)
            .getGoodsList(params)
            .subscribeOn(Schedulers.io())
            .unsubscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            //请求失败重连次数
            .retry(2)
            .subscribeBy(
                onError = {
                    LogUtils.e(it.toString())
                },
                onNext = {

                    it.data?.list?.forEachIndexed { _, goodsItemBean ->
                        goodsItemBean.imageSmall =
                            "${goodsItemBean.coverImg}?x-oss-process=image/resize,m_mfit,w_200,crop,h_200,w_200,h_200,g_center"
                    }

                    mRefreshView.isRefreshing = false
                    mAdapter.loadMoreModule.isEnableLoadMore = true

                    if (pageInfo.isFirstPage()) {
                        //如果是加载的第一页数据，用 setData()
                        it.data?.list?.let { it ->
                            mAdapter.setList(it)
                            Thread{DataCacheUtil.saveGoodsTreasureList(mAdapter.data)}.start()
                        }
                    } else {
                        //不是第一页，则用add
                        it.data?.list?.let { it ->
                            mAdapter.addData(it)
                            Thread{DataCacheUtil.saveGoodsTreasureList(mAdapter.data)}.start()
                        }
                    }

                    if (it.data?.list?.size!! < pageInfo.pageSize) {
                        //如果不够一页,显示没有更多数据布局
                        mAdapter.loadMoreModule.loadMoreEnd()
                    } else {
                        mAdapter.loadMoreModule.loadMoreComplete()
                    }
                    // page加一
                    pageInfo.nextPage()
                }
            )
    }

    override fun lazyData() {
        super.lazyData()
        // 进入页面，刷新数据
        if (goodsTreasureList.isEmpty()) {
            mRefreshView.isRefreshing = true
            refresh()
        }
    }

}